package com.wtwd.wtwddevice.deviceserver.handler.processimpl;

import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.*;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.deviceserver.handler.MsgHandlerFactory;
import com.wtwd.wtwddevice.deviceserver.handler.ProcessMessageHandler;
import com.wtwd.wtwddevice.deviceserver.model.DeviceSession;
import com.wtwd.wtwddevice.deviceserver.netty.LocalSessions;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
@MsgType(MsgTypeEnum.ALARM_POWER)
public class AlarmPowerHandler implements ProcessMessageHandler {
    @Override
    public WTProtocol processMsg(WTProtocol wtProtocol, Channel channel) {
        String deviceKey = wtProtocol.getImei();
        if (LocalSessions.getDeviceLoginSession(wtProtocol.getImei()) == null) {
            //设备未登录
            log.error("设备未登录异常{}-{}", wtProtocol.toString());
            return null;
        }
        MsgHandlerFactory.getMqSendMessage()
                .push(
                        MessageBase.builder()
                                .deviceKey(wtProtocol.getImei())
                                .wtProtocol(wtProtocol)
                                .build());

        //需要发送给app所以在这里回复
        String[] split = wtProtocol.getBody().split(SeparatorConstant.CMD_BODY_SEGMENTATION);

        if(split[0].equals(AlarmPowerConstant.AUTOMATIC_SHUTDOWN_ALARM) || split[0].equals(AlarmPowerConstant.SHUTDOWN_ALARM)){
            LocalSessions.removeByChannel(channel);
        }
        String s = String.valueOf(AnswerStateEnum.NORMAL.getState());
        wtProtocol.setTime(DateUtils.format(new Date(), DateUtils.dateFormat15));
        wtProtocol.setBody(s);
        wtProtocol.setBodyLength(s.length());
        wtProtocol.setMesType(String.valueOf(CmdTypeEnum.REPORT_RESPONSE.getCmdType()));
        return wtProtocol;
    }
}
